import React, { Component } from 'react';
import { connect } from 'dva';
import { Table, Input, Button, Icon, Pagination, Modal, message } from 'antd';
import styles from '../userManage/index.css';
import { Dispatch, AnyAction } from 'redux';
import { produce, Draft } from 'immer';
import {
  queryRole,
  queryChildRole,
  deleteRoleUser,
  insertUserRole
} from '@/services/systemDevice';
import { FormComponentProps } from 'antd/es/form';
import { router } from 'umi';
import _ from 'lodash';
import { isMenuVisible } from '@/utils/utils';

interface rolePsops extends FormComponentProps {
  loading: boolean;
  dispatch: Dispatch<AnyAction>;
  // childList?: Statistics;
  form: FormComponentProps['form'];
}
interface roleManager {
  pageTotal: number;
  filterQueryParams: any;
  title: any;
  params: any;
  showModel: boolean;
  kinds: any;
  list: any;
  isTrue: boolean;
  id: any;
  childListPower: any;
  roleName: any;
  powerParams: any;
  filterQueryParams1: any;
  params1: any;
  selectedRowKeys: any;
}
class roleManage extends Component<rolePsops, roleManager> {
  state: roleManager = {
    title: '', //删除内容提示
    filterQueryParams: {
      roleName: '',
      pageNum: 1,
      pageSize: 10,
      userId: this.props.match.params.userId,
    },
    filterQueryParams1: {
      roleName: '',
      pageNum: 1,
      pageSize: 10,
      userId: this.props.match.params.userId,
    },
    showModel: false,
    isTrue: false,
    list: {},
    childListPower: {},
    id: [],
    selectedRowKeys: [],
  };
  async componentWillMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'statistics/longDeviceType' });
    dispatch({ type: 'device/clearChildren' });
    this.handleFilterQuery();
  }
  handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 角色名称
    e.persist();
    this.setState(
      produce((draft: Draft<roleManager>): void => {
        draft.filterQueryParams.roleName = e.target.value;
      }),
    );
  };

  handleChangeBase = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 角色名称
    e.persist();
    this.setState(
      produce((draft: Draft<roleManager>): void => {
        draft.filterQueryParams1.roleName = e.target.value;
      }),
    );
  };
  handleFilterQuery = async () => {// 用户授权的所有角色
    // 搜索
    console.log(this.state.filterQueryParams);
    const [err, data] = await queryRole(this.state.filterQueryParams);
    if (!err) {
      this.setState(
        produce((draft: Draft<roleManager>): void => {
          draft.list = data;
        }),
      );
    }
  };
  handleFilterQuery1 = async () => {
    // 搜索
    console.log(this.state.filterQueryParams1);
    const [err, data] = await queryChildRole(this.state.filterQueryParams1);
    if(!err){
        this.setState(
            produce((draft: Draft<roleManager>): void => {
              draft.childListPower = data;
            }),
        );
    }
  };
  handleSure = async () => {
    // 确认删除
    const [err, data] = await deleteRoleUser({surUserIds: this.props.match.params.userId, surRoleId: this.state.id });
    if (!err) {
      this.setState(
        produce((draft: Draft<roleManager>): void => {
          draft.isTrue = false;
        }),
      );
      message.info('删除成功');
    } else {
      this.setState(
        produce((draft: Draft<roleManager>): void => {
          draft.isTrue = false;
        }),
      );
    }
    this.handleFilterQuery();
  };
  handleSigDelete = (record: any) => {
    // 删除
    this.setState(
      produce((draft: Draft<roleManager>): void => {
        draft.id = record.roleId;
      }),
    );
    this.setState(
      produce((draft: Draft<roleManager>): void => {
        draft.title = '确定要将选中数据取消授权吗？';
        draft.isTrue = true;
      }),
    );
  };
  handleAddDept = async () => {
    //新增
    const { dispatch } = this.props;
    this.setState(
      produce((draft: Draft<roleManager>): void => {
        draft.showModel = true;
        draft.filterQueryParams1.pageNum = 1;
      }),
    );
    this.handleFilterQuery1();
  };
  handleSubmit = async (e: any) => {
      this.setState(
        produce((draft: Draft<roleManager>): void => {
          draft.showModel = false;
        })
      );
      this.handleFilterQuery();
  };
  handleSigAdd = async(record: any) => {
    const [err, data] = await insertUserRole({ userIds: this.props.match.params.userId, roleId: record.roleId});
    if (!err) {
      message.info('添加成功');
      this.handleFilterQuery1();
    }
  };
  columns: any = [
    {
      title: '角色编号',
      dataIndex: 'roleId',
      key: 'roleId',
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName',
    },
    {
      title: '权限字符',
      dataIndex: 'roleKey',
      key: 'roleKey',
    },
    {
      title: '显示顺序',
      dataIndex: 'roleSort',
      key: 'roleSort',
    },
    {
        title: '角色状态',
        dataIndex: 'operateName',
        key: 'operateName',
        render: (text: any, record: any) => {
          return record.status == 0 ? (
            <span style={{ color: 'rgb(69, 235, 167)' }}>正常</span>
          ) : (
            <span style={{ color: '#cb3203' }}>停用</span>
          );
        },
      },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (text, record) => {
        return isMenuVisible('system:user:deleteUserRole') && (
          <span>
            <a onClick={() => {this.handleSigDelete(record);}} style={{ color: '#cb3203' }}>取消授权</a>
          </span>
        );
      },
    },
  ];
  childColumns: any = [
    {
        title: '角色编号',
        dataIndex: 'roleId',
        key: 'roleId',
    },
    {
        title: '角色名称',
        dataIndex: 'roleName',
        key: 'roleName',
    },
    {
        title: '权限字符',
        dataIndex: 'roleKey',
        key: 'roleKey',
    },
    {
        title: '显示顺序',
        dataIndex: 'roleSort',
        key: 'roleSort',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (text, record) => {
        return (
          <span className={styles.one}>
            <a
              onClick={() => {
                this.handleSigAdd(record);
              }}
            >
              添加
            </a>
          </span>
        );
      },
    },
  ];
  render() {
    return (
      <div className={`${styles.container} ${styles.dataContainer}`}>
        <div className={styles.containerTitle}>位置: 用户管理/分配角色</div>
        <div className={styles.userRight}>
          <div style={{ overflow: 'hidden' }}>
            <div className={styles['inforAnasy-container-top-btn']}>
              {
                isMenuVisible('system:user:insertUserRole') && <Button type="link" onClick={this.handleAddDept}>
                <Icon type="plus" />
                新增
              </Button>}
              <Button type="link" onClick={() => router.goBack()}>
                <Icon type="rollback" />
              </Button>
            </div>
            <div style={{ display: 'flex' }}>
              <div className={styles['dev-search-select']}>
                <Input
                  onChange={this.handleChange}
                  value={this.state.filterQueryParams.roleName}
                  addonBefore="角色名称"
                  type="text"
                />
              </div>
              <Button
                type="link"
                className={styles['search']}
                onClick={() => {
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.filterQueryParams.pageNum = 1;
                    }),
                    () => {
                      this.handleFilterQuery();
                    },
                  );
                }}
              >
                搜索
              </Button>
              <Button
                type="link"
                className={styles['search']}
                onClick={() => {
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.filterQueryParams.roleName = '';
                    }),
                  );
                }}
              >
                重置
              </Button>
            </div>
          </div>
          <Table
            scroll={{ y: '500px' }}
            pagination={false}
            columns={this.columns}
            dataSource={this.state.list.rows}
            rowKey="deviceId"
          />
          <div className="pagination-box">
            <Pagination
              defaultCurrent={this.state.filterQueryParams.pageNum}
              current={this.state.filterQueryParams.pageNum}
              onChange={pagenum => {
                this.setState(
                  produce((draft: Draft<roleManager>): void => {
                    draft.filterQueryParams.pageNum = pagenum;
                  }),
                  () => this.handleFilterQuery(),
                );
              }}
              total={this.state.list.total ? this.state.list.total : 0}
            />
            <span className="pagination-title-box">
              第{this.state.filterQueryParams.pageNum}/
              {Math.ceil(
                (this.state.list.total ? this.state.list.total : 0) /
                  this.state.filterQueryParams.pageSize,
              )}
              页 共{this.state.list.total ? this.state.list.total : 0}条
            </span>
          </div>
          <Modal
            title="新增角色"
            visible={this.state.showModel}
            className="porwer-modal addRole"
            onCancel={() => {
              this.setState({
                showModel: false,
                filterQueryParams1: {
                  userId: this.props.match.params.userId,
                  pageNum: 1,
                  pageSize: 10,
                },
              });
              this.handleFilterQuery();
            }}
          >
            <div style={{ overflow: 'hidden' }}>
              <div style={{ display: 'flex' }}>
                <div className={styles['dev-search-select']}>
                  <Input
                    onChange={this.handleChangeBase}
                    value={this.state.filterQueryParams1.roleName}
                    addonBefore="角色名称"
                    type="text"
                  />
                </div>
                <Button
                  type="link"
                  className={styles['search']}
                  onClick={() => {
                    this.setState(
                      produce((draft: Draft): void => {
                        draft.filterQueryParams1.pageNum = 1;
                      }),
                      () => {
                        this.handleFilterQuery1();
                      },
                    );
                  }}
                >
                  搜索
                </Button>
                <Button
                  type="link"
                  className={styles['search']}
                  onClick={() => {
                    this.setState(
                      produce((draft: Draft): void => {
                        draft.filterQueryParams1.roleName = '';
                      }),
                    );
                  }}
                >
                  重置
                </Button>
              </div>
            </div>
            <div className={styles.childName}>
              <Table
                scroll={{ y: '220px' }}
                pagination={false}
                columns={this.childColumns}
                dataSource={this.state.childListPower.rows}
                // rowSelection={rowSelection}
              />
            </div>
            <div className="pagination-box">
              <Pagination
                defaultCurrent={this.state.filterQueryParams1.pageNum}
                current={this.state.filterQueryParams1.pageNum}
                onChange={pagenum => {
                  this.setState(
                    produce((draft: Draft<roleManager>): void => {
                      draft.filterQueryParams1.pageNum = pagenum;
                      draft.selectedRowKeys = [];
                    }),
                    () => this.handleFilterQuery1(),
                  );
                }}
                total={this.state.childListPower.total ? this.state.childListPower.total : 0}
              />
              <span className="pagination-title-box">
                第{this.state.filterQueryParams1.pageNum}/
                {
                  Math.ceil(
                    (this.state.childListPower.total ? this.state.childListPower.total : 0) /
                      this.state.filterQueryParams1.pageSize,
                  )
                }
                页 共{this.state.childListPower.total ? this.state.childListPower.total : 0}条
              </span>
            </div>
            <div className={styles.footBtnArea}>
              <div
                style={{ marginRight: '30px' }}
                className={styles.foot_btn}
                onClick={this.handleSubmit}
              >
                确认
              </div>
              <div
                className={styles.foot_btn}
                onClick={() => {
                  this.setState({
                    showModel: false,
                  });
                  this.setState(
                    produce((draft: Draft): void => {
                      draft.filterQueryParams1.roleName = '';
                    }),
                  );
                  this.handleFilterQuery();
                }}
              >
                取消
              </div>
            </div>
          </Modal>
          <Modal
            title="系统提示"
            className={`${styles.modal} ${styles.deleteBox}`}
            visible={this.state.isTrue}
            onCancel={() => {
              this.setState({ isTrue: false });
            }}
          >
            <div className={styles.titles}>{this.state.title}</div>
            <div className={styles.footBtn}>
              <div
                style={{ marginRight: '30px' }}
                className={styles.foot_btn}
                onClick={this.handleSure}
              >
                确定
              </div>
              <div
                className={styles.foot_btn}
                onClick={() => {
                  this.setState({ isTrue: false });
                }}
              >
                取消
              </div>
            </div>
          </Modal>
        </div>
      </div>
    );
  }
}
export default connect(({ loading, statistics, device }: any) => {
  return {
    loading: loading.effects['statistics/deviceList'],
  };
})(roleManage);
